package com.gqzdev.xblog.controller.admin;

import com.gqzdev.xblog.entity.Ad;
import com.gqzdev.xblog.page.Page;
import com.gqzdev.xblog.service.AdService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * (Ad)表控制层
 *
 * @author ganquanzhong
 * @since 2020-05-31 21:08:54
 */
@RestController
@RequestMapping("/admin/ad/")
public class AdController {
    /**
     * 服务对象
     */
    @Resource
    private AdService adService;

    @Value("${xblog.file.path}")
    private String filePath;

    @Value("${xblog.server.path}")
    private String serverPath;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    public Ad selectOne(Integer id) {
        return this.adService.queryById(id);
    }

    @RequestMapping(value="/list",method= RequestMethod.GET)
    public ModelAndView list(ModelAndView model){
        Map<String,Object> queryMap = new HashMap<String, Object>();
        queryMap.put("offset", 0);
        queryMap.put("pageSize", 999);
        model.addObject("adList", adService.findList(queryMap));
        model.setViewName("ad/list");
        return model;
    }

    /**
     * 分页模糊搜索查询列表
     * @param page
     * @return
     */
    @RequestMapping(value="/list",method= RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> getList(
            @RequestParam(name="name",required=false,defaultValue="") String name,
            @RequestParam(name="type",required=false,defaultValue="") Integer type,
            Page page
    ){
        Map<String,Object> ret = new HashMap<String, Object>();
        Map<String,Object> queryMap = new HashMap<String, Object>();
        queryMap.put("name", name);
        queryMap.put("type", type);
        queryMap.put("offset", page.getOffset());
        queryMap.put("pageSize", page.getRows());
        ret.put("rows", adService.findList(queryMap));
        ret.put("total", adService.getTotal(queryMap));
        return ret;
    }

    /**
     *  ad 添加页面
     */
    @RequestMapping(value="/add",method= RequestMethod.GET)
    public ModelAndView add(ModelAndView model){
        model.setViewName("ad/add");
        return model;
    }

    @RequestMapping(value="/add",method= RequestMethod.POST)
    @ResponseBody
    public Map<String,String> add(Ad ad){
        Map<String,String> ret = new HashMap<String, String>();
        if(ad == null){
            ret.put("type", "error");
            ret.put("msg", "请填写正确的信息！");
            return ret;
        }
        if(StringUtils.isEmpty(ad.getName())){
            ret.put("type", "error");
            ret.put("msg", "名称不能为空！");
            return ret;
        }
        //type==3 为链接类型
        if(ad.getType()!=3 && StringUtils.isEmpty(ad.getContent())){
            ret.put("type", "error");
            ret.put("msg", "内容不能为空！");
            return ret;
        }
        if(ad.getType()!=3 && StringUtils.isEmpty(ad.getPath())){
            ret.put("type", "error");
            ret.put("msg", "图片必须上传！");
            return ret;
        }
        ad.setCreatetime(new Date());
        Ad ad1 = adService.insert(ad);
        if(null == ad1){
            ret.put("type", "error");
            ret.put("msg", "添加失败，请联系管理员！");
            return ret;
        }
        ret.put("type", "success");
        ret.put("msg", "添加成功！");
        return ret;
    }

    @RequestMapping(value="/upload_ad_photo",method= RequestMethod.POST)
    @ResponseBody
    public Map<String, String> uploadPhoto(MultipartFile photo, HttpServletRequest request){
        Map<String, String> ret = new HashMap<String, String>();
        if(photo == null){
            ret.put("type", "error");
            ret.put("msg", "选择要上传的文件！");
            return ret;
        }
        if(photo.getSize() > 1024*1024*1024){
            ret.put("type", "error");
            ret.put("msg", "文件大小不能超过10M！");
            return ret;
        }
        //获取文件后缀
        String suffix = photo.getOriginalFilename().substring(photo.getOriginalFilename().lastIndexOf(".")+1,photo.getOriginalFilename().length());
        if(!"jpg,jpeg,gif,png".toUpperCase().contains(suffix.toUpperCase())){
            ret.put("type", "error");
            ret.put("msg", "请选择jpg,jpeg,gif,png格式的图片！");
            return ret;
        }
        //String savePath = request.getServletContext().getRealPath("/") + "/resources/upload/";

        //图片文件存放位置
        String savePath=filePath+"ad/";

        //判断文件目录是否存在
		File savePathFile = new File(savePath);
		if(!savePathFile.exists()){
			//若不存在改目录，则创建目录
			savePathFile.mkdir();
		}
        String filename = System.currentTimeMillis() +"."+suffix;
        String path =savePath+filename;
        try {
            //将文件保存至指定目录
            photo.transferTo(new File(path));
        }catch (Exception e) {
            // TODO Auto-generated catch block
            ret.put("type", "error");
            ret.put("msg", "文件上传异常！");
            e.printStackTrace();
            return ret;
        }
        ret.put("type", "success");
        ret.put("msg", "文件上传成功！");
        ret.put("filepath",serverPath+"/upload/" + filename );
        return ret;
    }

    /**
     * edit ad
     */

    @RequestMapping(value="/edit",method= RequestMethod.GET)
    public ModelAndView edit(ModelAndView model, Integer id){
        model.addObject("ad", adService.queryById(id));
        model.setViewName("ad/edit");
        return model;
    }

    @RequestMapping(value="/edit",method= RequestMethod.POST)
    @ResponseBody
    public Map<String,String> edit(Ad ad){
        Map<String,String> ret = new HashMap<String, String>();
        if(ad == null){
            ret.put("type", "error");
            ret.put("msg", "请填写正确的信息！");
            return ret;
        }
        if(StringUtils.isEmpty(ad.getName())){
            ret.put("type", "error");
            ret.put("msg", "名称不能为空！");
            return ret;
        }
        if(StringUtils.isEmpty(ad.getContent())){
            ret.put("type", "error");
            ret.put("msg", "内容不能为空！");
            return ret;
        }
        if(StringUtils.isEmpty(ad.getPath())){
            ret.put("type", "error");
            ret.put("msg", "图片必须上传！");
            return ret;
        }
        ad.setCreatetime(new Date());
        Ad ad1 = adService.update(ad);
        if(null == ad1){
            ret.put("type", "error");
            ret.put("msg", "更新失败，请联系管理员！");
            return ret;
        }
        ret.put("type", "success");
        ret.put("msg", "更新成功！");
        return ret;
    }

    @RequestMapping(value="/delete",method= RequestMethod.POST)
    @ResponseBody
    public Map<String,String> delete(String ids){
        Map<String,String> ret = new HashMap<String, String>();
        if(StringUtils.isEmpty(ids)){
            ret.put("type", "error");
            ret.put("msg", "请选择要删除的信息！");
            return ret;
        }
        if(ids.contains(",")){
            ids = ids.substring(0,ids.length()-1);
        }
        try{
            if(adService.delete(ids) <= 0){
                ret.put("type", "error");
                ret.put("msg", "删除失败，请联系管理员！");
                return ret;
            }
        }catch(Exception e){
            ret.put("type", "error");
            ret.put("msg", "删除失败！");
            return ret;
        }
        ret.put("type", "success");
        ret.put("msg", "删除成功！");
        return ret;
    }

    @RequestMapping(value="/check",method= RequestMethod.POST)
    @ResponseBody
    public Map<String,String> check(String ids){
        Map<String,String> ret = new HashMap<String, String>();
        if(StringUtils.isEmpty(ids)){
            ret.put("type", "error");
            ret.put("msg", "请选择要check的信息！");
            return ret;
        }
        if(ids.contains(",")){
            ids = ids.substring(0,ids.length()-1);
        }
        try{
            if(adService.check(ids) <= 0){
                ret.put("type", "error");
                ret.put("msg", "check失败，请联系管理员！");
                return ret;
            }
        }catch(Exception e){
            ret.put("type", "error");
            ret.put("msg", "check失败！");
            return ret;
        }
        ret.put("type", "success");
        ret.put("msg", "check成功！");
        return ret;
    }

    /**
     * 根据type 获取ad
     */

    @RequestMapping(value = "/get_sidebar_ad",method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> getSidebarAd(Integer type,Integer size) {
        Map<String, Object> ret = new HashMap<String, Object>();
        Map<String, Object> queryMap = new HashMap<String, Object>();
        queryMap.put("type", type);
        queryMap.put("offset", 0);
        queryMap.put("pageSize", size);
        ret.put("type", "success");
        ret.put("SidebarAdList", adService.findListShow(queryMap));
        return ret;
    }
}